package com.gzu.shop.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gzu.shop.base.BaseController;
import com.gzu.shop.common.Result;
import com.gzu.shop.common.ResultStatus;
import com.gzu.shop.constant.MessageConstant;
import com.gzu.shop.constant.StatusConstant;
import com.gzu.shop.entity.ClassificationSecond;
import com.gzu.shop.entity.Order;
import com.gzu.shop.entity.Thing;
import com.gzu.shop.exception.ThingBusinessException;
import com.gzu.shop.mapper.ClassificationSecondMapper;
import com.gzu.shop.mapper.OrderMapper;
import com.gzu.shop.mapper.ThingMapper;
import com.gzu.shop.param.SearchCondition;
import com.gzu.shop.service.ThingService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author Clown
 */

@Tag(name = "商品管理接口")
@RestController
@Slf4j
@RequestMapping("/thing")
@AllArgsConstructor
public class ThingController extends BaseController<ThingService, Thing> {
    private ThingService thingService;
    private ThingMapper thingMapper;
    private OrderMapper orderMapper;
    private ClassificationSecondMapper classificationSecondMapper;
    // 实时推荐，用户点击收藏，添加心愿，下单，调用方法，重新计算推荐
   @GetMapping("/recommend")
    public Result<List<Thing>> recommend() {
       List<Thing> result = thingService.recommend();
       return Result.success(ResultStatus.SUCCESS, result);
   }

   // 离线推荐
    @GetMapping("/offlineRecommend")
    public Result<List<Thing>> offlineRecommend() {
        List<Thing> result = thingService.offlineRecommend();
        return Result.success(ResultStatus.SUCCESS, result);

    }

    @Override
    @Operation(summary = "判断非法值")
    @PostMapping("/add")
    public Result<Void> addEntity(@RequestBody Thing entity) {
        // 数据为空
        if (Objects.isNull(entity)) {
            throw new ThingBusinessException(MessageConstant.DATA_IS_NULL);
        }

        // 如果商品名已经为空或者已经存在
        if (entity.getTitle() == null || entity.getTitle().isEmpty()
                || thingMapper.exists(new QueryWrapper<Thing>()
                .eq("title", entity.getTitle()))) {
            throw new ThingBusinessException(MessageConstant.TITLE_EXISTS_OR_EMPTY);
        }
        // 不存在二级标签
        if (entity.getClassificationSecondId() == null) {
            throw new ThingBusinessException(MessageConstant.SECOND_CATEGORY_EMPTY);
        }

        // 如果收藏数、心愿数、点赞数、PV、score、price、status、repertory为空就置为0
        if (entity.getWishCount() == null || entity.getWishCount().isEmpty()) {
            entity.setWishCount(String.valueOf(0));
        }
        if (entity.getCollectCount() == null || entity.getCollectCount().isEmpty()) {
            entity.setCollectCount(String.valueOf(0));
        }
        if (entity.getRecommendCount() == null || entity.getRecommendCount().isEmpty()) {
            entity.setRecommendCount(String.valueOf(0));
        }
        if (entity.getPv() == null || entity.getPv().isEmpty()) {
            entity.setPv(String.valueOf(0));
        }
        if (entity.getScore() == null || entity.getScore().isEmpty()) {
            entity.setScore(String.valueOf(0));
        }
        if (entity.getStatus() == null || entity.getStatus().isEmpty()) {
            entity.setStatus(StatusConstant.CLOSE);
        }
        if (entity.getRepertory() == null || entity.getRepertory().isEmpty()) {
            entity.setRepertory(String.valueOf(0));
        }
        if (entity.getPrice() == null || entity.getPrice().isEmpty()) {
            entity.setPrice(String.valueOf(0));
        }
        // 设置时间
        entity.setCreateTime(String.valueOf(System.currentTimeMillis()));
        entity.setUpdateTime(String.valueOf(System.currentTimeMillis()));
        return super.addEntity(entity);
    }

    @Override
    @Operation(summary = "判断非法值")
    @PostMapping("/edit")
    public Result<Void> editById(@RequestBody Thing entity) {
        // 数据为空
        if (Objects.isNull(entity)) {
            throw new ThingBusinessException(MessageConstant.DATA_IS_NULL);
        }

        // 如果商品名已经存在
        if (thingMapper.exists(new QueryWrapper<Thing>().eq("title", entity.getTitle()))) {
            throw new ThingBusinessException(MessageConstant.TITLE_EXISTS_OR_EMPTY);
        }
        entity.setUpdateTime(String.valueOf(System.currentTimeMillis()));
        return super.editById(entity);
    }


    @Override
    @Operation(summary = "重新封装数据")
    @PostMapping("/page/{startPage}/{pageSize}")
    public Result<IPage<Thing>> page(@PathVariable int startPage,
                                     @PathVariable int pageSize,
                                     @RequestBody(required = false) SearchCondition<Thing> searchCondition) {
        Result<IPage<Thing>> page = super.page(startPage, pageSize, searchCondition);
        List<Thing> records = page.getData().getRecords();

        log.info("searchCondition:{}", searchCondition);
        // 数据为空
//        if (records.isEmpty()) {
//            return Result.success(ResultStatus.SUCCESS, null);
//        }

        for (Thing thing : records) {
            ClassificationSecond classificationSecond = classificationSecondMapper.selectOne(new QueryWrapper<ClassificationSecond>()
                    .eq("id", thing.getClassificationSecondId()));
            thing.setClassificationSecondName(classificationSecond.getTitle());
        }


        page.getData().setRecords(records);
        return page;
    }

    @Operation(summary = "重新封装数据")
    @PostMapping("/searchAllOrders")
    public Result<List<Order>> searchAllOrders(@RequestBody(required = false) SearchCondition<Thing> searchCondition) {
        // 取出数据
        Result<List<Thing>> listResult = super.searchAll(searchCondition);
        List<Thing> data = listResult.getData();
        // 重新封装数据
        List<List<Order>> tempOrders = new ArrayList<>();
        for (Thing thing : data) {
            tempOrders.add(orderMapper.selectList(new QueryWrapper<Order>().eq("thing_id", thing.getId())));
        }
        ArrayList<Order> orders = new ArrayList<>();
        for (List<Order> orders1 : tempOrders) {
            orders.addAll(orders1);
        }
        return Result.success(ResultStatus.SUCCESS, orders);
    }


    @Override
    @Operation(summary = "实现通过id删除功能")
    @DeleteMapping("/del/{id}")
    public Result<Void> deleteById(@PathVariable Long id) {
        // 判断商品关联的订单是否还存在
        isOrderExist(id);
        return super.deleteById(id);
    }

    @Override
    @Operation(summary = "实现批量删除功能")
    @DeleteMapping("/deleteBatch")
    public Result<Void> deleteBatch(@RequestBody List<Long> ids) {
        // 判断商品关联的订单是否还存在
        for (Long id : ids) {
            isOrderExist(id);
        }
        return super.deleteBatch(ids);
    }

    @Operation(summary = "判断商品是否还存在订单")
    private void isOrderExist(Long id) {
        if (orderMapper.exists(new QueryWrapper<Order>()
                .eq("thing_id", id))) {
            throw new ThingBusinessException(MessageConstant.THING_ORDER_EXISTS);
        }
    }
}
